package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.commom.Constant;
import com.itheima.reggie.commom.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @author Sea
 * @date 2023/3/1 19:38
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private HttpSession session;

    @Override
    public ResultInfo login(String username, String password) {
        Employee employee = employeeMapper.findByUsername(username);
        if (employee == null) {
            return ResultInfo.error("此用户不存在");
        }
        String s = SecureUtil.md5(password);
        if (!StrUtil.equals(s, employee.getPassword())) {
            return ResultInfo.error("密码错误");
        }
        if (employee.getStatus()!=1){
            return ResultInfo.error("此账号");
        }
        session.setAttribute(Constant.SESSION_EMPLOYEE,employee);
      return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> find(String name) {
        return employeeMapper.find(name);
    }

    @Override
    public void save(Employee employee) {
        //1.补全信息
        //1-1雪花
        long empolyeeId= IdUtil.createSnowflake(1,1).nextId();
        employee.setId(empolyeeId);
        //1-2初始密码
        String md5 = SecureUtil.md5(Constant.INIT_PASSWORD);
        employee.setPassword(md5);
        //1-3 员工状态
        employee.setStatus(Employee.STATUS_DISABLE);
        //1-4 创建时间
//        employee.setCreateTime(new Date());
//        employee.setUpdateTime(new Date());
        //1-5 创建。修改人
//        Employee employee1 = (Employee) session.getAttribute(Constant.SESSION_EMPLOYEE);;
//        employee.setCreateUser(employee1.getId());
//        employee.setUpdateUser(employee1.getId());
        //2.mapper 保存
        employeeMapper.save(employee);
    }

    @Override
    public Employee findId(Long id) {
        return employeeMapper.findId(id);
    }

    @Override
    public void update(Employee employee) {
//        employee.setUpdateTime(new Date());
//        Employee employee1 = (Employee) session.getAttribute(Constant.SESSION_EMPLOYEE);
//        employee.setUpdateUser(employee1.getId());

        employeeMapper.update(employee);
    }

}
